package com.lhkj.ct.quartz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.lhkj.ct.base.annntation.Log;
import com.lhkj.ct.base.constants.Constants;
import com.lhkj.ct.base.enums.ActionType;
import com.lhkj.ct.base.exception.job.TaskException;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.base.model.ro.ActionResult;
import com.lhkj.ct.base.validator.group.ValGroups;
import com.lhkj.ct.quartz.model.entity.TblJob;
import com.lhkj.ct.quartz.service.QuartzJobService;
import com.lhkj.ct.quartz.util.CronUtils;
import com.lhkj.ct.quartz.util.ScheduleUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 调度任务信息操作处理
 */
@RestController
@RequestMapping("api/system/job")
@Api(tags = "14.定时任务")
@ApiSupport(order = 14)
public class SysJobController {

    @Resource
    private QuartzJobService jobService;

    /**
     * 查询定时任务列表
     */
//    //@RequiresPermissions("@ss.hasPermi('monitor:job:list')")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "定时任务列表")
    @GetMapping("/list")
    public ActionResult<IPage<TblJob>> list(TblJob job, PageQuery pageQuery) {
        return ActionResult.success(jobService.selectJobPage(job, pageQuery));
    }

    /**
     * 获取定时任务详细信息
     */
//    //@RequiresPermissions("monitor:job:query")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "任务详细信息")
    @GetMapping(value = "/{jobId}")
    public ActionResult<TblJob> getInfo(@PathVariable("jobId") String jobId) {
        return ActionResult.success(jobService.selectById(jobId));
    }

    /**
     * 新增定时任务
     */
//    //@RequiresPermissions("@ss.hasPermi('monitor:job:add')")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "新增定时任务")
    @Log(title = "定时任务", actionType = ActionType.INSERT)
    @PostMapping("insert")
    public ActionResult<Void> add(@Validated(value = {ValGroups.Insert.class}) @RequestBody TblJob job) throws TaskException, SchedulerException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return ActionResult.fail("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return ActionResult.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return ActionResult.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return ActionResult.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return ActionResult.fail("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return ActionResult.fail("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        return ActionResult.judge(jobService.insertJob(job));
    }

    /**
     * 修改定时任务
     */
//    //@RequiresPermissions("@ss.hasPermi('monitor:job:edit')")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "修改定时任务")
    @Log(title = "定时任务", actionType = ActionType.UPDATE)
    @PutMapping("update")
    public ActionResult<Void> edit(@Validated(value = {ValGroups.Update.class}) @RequestBody TblJob job) throws TaskException, SchedulerException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return ActionResult.fail("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return ActionResult.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return ActionResult.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return ActionResult.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return ActionResult.fail("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return ActionResult.fail("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        return ActionResult.judge(jobService.updateJob(job));
    }

    /**
     * 定时任务状态修改
     */
//    //@RequiresPermissions("@ss.hasPermi('monitor:job:changeStatus')")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "任务状态修改")
    @Log(title = "定时任务", actionType = ActionType.UPDATE)
    @PutMapping("/changeStatus")
    public ActionResult<Void> changeStatus(@RequestBody TblJob job) throws SchedulerException {
        TblJob newJob = jobService.selectById(job.getId());
        newJob.setStatus(job.getStatus());
        return ActionResult.judge(jobService.changeStatus(newJob));
    }


    /**
     * 定时任务立即执行一次
     */
//    //@RequiresPermissions("@ss.hasPermi('monitor:job:changeStatus')")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "定时任务立即执行一次")
    @Log(title = "定时任务", actionType = ActionType.UPDATE)
    @PutMapping("/run")
    public ActionResult<Void> run(@RequestBody TblJob job) throws SchedulerException {
        boolean result = jobService.run(job);
        return result ? ActionResult.success() : ActionResult.fail("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
//    //@RequiresPermissions("@ss.hasPermi('monitor:job:remove')")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "删除定时任务")
    @Log(title = "定时任务", actionType = ActionType.DELETE)
    @DeleteMapping("/delete")
    public ActionResult<Void> remove(@RequestBody List<String> jobIds) throws SchedulerException {
        jobService.deleteJobByIds(jobIds);
        return ActionResult.success();
    }
}
